<template>
  <div>
    <div class="title font14 ma30-15">
      <p>个人资料</p>
    </div>
    <div class="bor7 pa15">
      <el-form
        :model="ruleForm"
        :rules="ruleFormRules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="头像"
          prop="avatar"
          class="font12 huodonghaibao"
          required
        >
          <!-- <img src="../../img/2.jpg" alt /> -->
          <el-row :gutter="20">
            <el-col   class="p_l_no">
              <el-upload
                class="upload-demo"
                drag
                action="#"
                ref="upload"
                :file-list="files"
                :http-request="handleUpload"
                :auto-upload="true"
              >
                <div class="grid-content bg-purple">
                  <img
                    v-if="imageUrl"
                    :src="imageUrl"
                    v-model="ruleForm.avatar"
                    class="avatar w100"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </div>
              </el-upload>
            </el-col>
            <el-col :span="6" class="p_lr_100">
              <div class="grid-content bg-purple font12">
                <div class="bg-purple-text">
                  <p class="colred">温馨提示</p>
                  上传的头像会自动生成头像缩略图，您也可以拖动大图的裁
剪区域，调整缩略图内容。支持JPG/GIF/PNG等图片格式<br>
推荐尺寸：180*180像素
                  <div>
                    <!--el-button @click="CancelUpload">取 消</el-button-->
                    <!--el-button
                      type="primary"
                      class="primary"
                      @click="fileChange"
                      >上传海报</el-button-->
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="昵称" prop="nickname" class="w50">
          <el-input
            v-model="ruleForm.nickname"
            placeholder="请输入您的昵称"
          ></el-input>
        </el-form-item>

        <el-form-item label="真实姓名" prop="name" class="w50">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入您的真实姓名"
          ></el-input>
        </el-form-item>

        <el-form-item label="手机号码" class="w50">
          <el-input
  v-model="ruleForm.mobile"
  :disabled="true">
</el-input>
        </el-form-item>

        <el-form-item label="电子邮箱" prop="email" class="w50">
          <el-input
            v-model="ruleForm.email"
            placeholder="请输入您的电子邮箱"
          ></el-input>
          <!--el-button type="primary">删除</el-button-->
        </el-form-item>

        <el-form-item label="城市"  class="font12 w50 chengshi">
          <vCity ref="getConCity" :setCity="ruleForm.city"  :key="ruleForm.city"></vCity>
        </el-form-item>

        <el-form-item label="自我介绍" prop="bio" class="w50">
          <el-input
            type="textarea"
            v-model="ruleForm.bio"
            placeholder="请用一句话介绍自己"
            class="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="submit"
            class="baocun"
            @click="handleSubmit">
            确认修改
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { regionData, CodeToText, TextToCode } from "element-china-area-data";
import vCity from "../../components/City.vue";

export default {
  components: {
    vCity,
  },
  data() {
    return {
      imageUrl: "",
      files: [],
      ruleForm: [],
      ruleFormRules: {
        avatar: [{ required: true, message: "头像必填", trigger: "blur" }],
        nickname: [{ required: true, message: "昵称必填", trigger: "blur" },{ min:2, max: 12, message: "昵称长度2-12位" }],
        name: [{ required: true, message: "真实姓名必填", trigger: "blur" },{ min:2, max: 12, message: "长度2-12位" }],
        email: [
          {
            required: true, message: "邮件地址必填",trigger: "click",
          },
        ],
        city: [{ required: true, message: "城市必填", trigger: "blur" }],
        bio: [{ required: true, message: "自我介绍必填", trigger: "blur" }],
      },
      options: regionData,
      selectedOptions: [],
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("图片尺寸 180*180，.jpg 或 .png格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片尺寸不能超过 4M!");
      }
      return isJPG && isLt2M;
    },
    handleChange(value) {
      //console.log(value);
      var provinceCode = CodeToText[value[0]];
      var cityCode = CodeToText[value[1]];
      var orgion = CodeToText[value[2]];
      ////console.log(provinceCode)
      ////console.log(cityCode)
      ////console.log(orgion)
      this.ruleForm.city = [value[0], value[1], value[2]];
      this.ruleForm.city_text = provinceCode + "/" + cityCode + "/" + orgion;
    },
    //提交
    handleSubmit() {
      this.$nextTick(() => {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {


            if (
              !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(
                this.ruleForm.email
              )
            ) {
              this.$message.error("邮箱格式不正确");
              return;
            }

            if (!this.$refs["getConCity"].city) {
              this.$message.error("请输入所在城市");
              return false;
            }

            //console.log(this.ruleForm);
            //定义一个json示例

            var url = this.$api + "/api/user/profile";
            var jsons = {
              avatar: this.ruleForm.avatar,
              nickname: this.ruleForm.nickname,
              name: this.ruleForm.name,
              email: this.ruleForm.email,
              city: this.$refs["getConCity"].city,
              bio: this.ruleForm.bio,
            };

            var that = this;

            this.$axios
              .post(url, jsons)
              .then((res) => {
                //console.log(res.data);
                if (res.data.code == 1) {
                  that.$message({
                    message: res.data.msg,
                    type: "success",
                  });
                  that.getUserInfo();
                } else {
                  that.$message.error(res.data.msg);
                }
              })
              .catch((Error) => {
                //console.log(Error);
                that.$message.error(Error);
              });
          }
        });
      })
    },
    //上传文件开始
    handleUpload(raw) {
      this.files.push(raw.file);
      this.fileChange();
      //console.log('handleUpload');
    },
    async fileChange() {
      //console.log(this.files);
      if (this.files.length > 1) {
        //this.$message.warning(`当前限制只能上传选择 1 个文件`);
        return;
      } else {
      }
      const loading = this.$loading({
        lock: true,
        text: "上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$refs.upload.submit(); // 这里是执行文件上传的函数，其实也就是获取我们要上传的文件
      let random = Math.random();
      let formData = new FormData();
      // formData.append("file", param.file);
      //formData.append("user_id", localStorage.user_id);
      this.files.forEach(function (file) {
        formData.append("file", file); // 因为要上传多个文件，所以需要遍历一下才行
        //不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
      });
      let res = await this.$axios.post(
        this.$api + `/api/common/upload`,
        formData
      );
      //console.log(res);
      // JSON.parse(res)
      if (res.data.code == 1) {
        this.$refs.upload.clearFiles();
        this.files = [];
        let objList = [];
        loading.close();
        this.imageUrl = this.$api + res.data.data.url;
        this.$set(this.ruleForm,'avatar',res.data.data.url);
      } else {
        loading.close();
        this.$message.error("上传文件失败" + res.data.msg);
      }
    },
    handExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    CancelUpload() {
      this.files = [];
      this.$refs.upload.clearFiles();
    },
    handFileSuccess(file) {
      //console.log(file);
      this.files = [];
      this.$refs.upload.clearFiles();
    },
    handleRemove(file, fileList) {
      // //console.log(file, fileList);
      this.files = fileList;
    },
    beforeRemove(file, fileList) {
      // //console.log(file, fileList);
    },
    getUserInfo() {
      var that = this;
      this.$axios
        .get(this.$api + "//api/user/userinfo")
        .then(function (response) {
          that.ruleForm = response.data.data;
          that.imageUrl = that.$api + response.data.data.avatar;

          //城市分开
          var tcity = that.ruleForm.city;
          that.ruleForm.city_text = that.ruleForm.city;
          var tcity = tcity.split("/");
          var code1 = TextToCode[tcity[0]].code;
          var code2 = TextToCode[tcity[0]][tcity[1]].code;
          var code3 = TextToCode[tcity[0]][tcity[1]][tcity[2]].code;
          that.ruleForm.city = [code1, code2, code3];

          //console.log("info", response.data.data);
        })
        .catch(function (error) {
          //console.log(error);
        });
    },
  },
  mounted() {
    this.getUserInfo();
  },
};
</script>

<style scoped>
html {
  height: 100% !important;
  overflow-y: hidden !important;
}
.demo-ruleForm .email .el-input {
  width: 88%;
  float: left;
}
.demo-ruleForm .email button {
  float: right;
  width: 10%;
  padding-left: 0;
  padding-right: 0;
}
.avatar.w100 {
object-fit: cover;
    width: 100% !important;
}
.p_l_no {
  padding-left: 0 !important;
}
.p_l_no {
  width: 190px !important;
  height: 180px;
}
.chengshi .el-cascader--large {
  width: 100% !important;
}
</style>
